<template>
  <div>
    <el-form
      ref="roleForm"
      :model="roleForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="roleForm.description" />
      </el-form-item>
      <el-form-item>
        <!-- 底部 -->
        <el-button size="small">取消</el-button>
        <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addRole, updateRole } from '@/api/setting.js'
export default {
  name: '',
  props: {
    isEdit: {
      type: Boolean
    },
    row: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    isEdit: {
      handler(newVal) {
        if (newVal) {
          // 表示点击的是：编辑进入的===表单需要显示数据
          this.roleForm = JSON.parse(JSON.stringify(this.row))
        }
      },
      immediate: true //  显示对话框就立即执行
    }
  },
  methods: {
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          // 校验满足条件
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    async doAdd() {
      const res = await addRole(this.roleForm)
      console.log(`res`, res)
      if (res.code === 10000) {
        // 成功后===
        this.$emit('success')
      }
    },
    async doEdit() {
      const res = await updateRole(this.roleForm)
      if (res.code === 10000) {
        // 成功后===
        this.$emit('success')
      }
    },
    close() {
      // 清空数据
      this.roleForm = {
        name: '',
        description: ''
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
